<?php
namespace Ntxx\Controller;
use Think\Controller;
class AnswerController extends Controller {
	private $sessionKey = "ntxx_answer_session";
	private $data = false;
	public function _initialize(){
		$data = session($this->sessionKey);
		if($data) $this->data = $data;
	}

	public function toanswer(){
        if(!in_app()){
            $result["info"]="请在掌中九江APP中参与竞答。";
            $result["status"]=0;
            $this->ajaxReturn($result);
            exit();
        }
//        $exam = I("post.exam");
        $startTime = "2018-01-21  00:00:00";
        $finishTime = "2018-01-30 23:59:59";
        if(strtotime ( $startTime ) > time ()) {
            $result["info"]="答题尚未开始";
            $result["status"]=0;
            $this->ajaxReturn($result);
        }
        elseif(strtotime ( $finishTime ) < time ()){
            $result["info"]="答题已于".$finishTime."结束。";
            $result["status"]=0;
            $this->ajaxReturn($result);
        }


        $group = I("post.group");
        $tname = I("post.tname");
        $pphone = I("post.pphone");

        $token = session("ntxx_token");


        if(!$group){
            $result["info"]="请选择您的单位";
            $result["status"]=0;
            $this->ajaxReturn($result);
        }

        if(!$tname){
            $result["info"]="请填写您的姓名";
            $result["status"]=0;
            $this->ajaxReturn($result);
        }

        if(!$pphone){
            $result["info"]="请填写您的联系方式";
            $result["status"]=0;
            $this->ajaxReturn($result);
        }
        $Testee = M("testee");

        $duplicate = $Testee->where(['pphone'=>array('NEQ',$pphone),
            "token"=>$token])->where("token!= '' and token != '(null)' and token != 'null'")->find();
        if($duplicate){
            $result["info"]="您的手机已于".$duplicate["finishtime"]."答过题，当时的手机号为".$duplicate["pphone"]."。错误码：".$token;
            $result["status"]=0;
            $this->ajaxReturn($result);
        }

        $testee = $Testee->getByPphone($pphone);
        if(!$testee){
            $data = [
                "group"=>$group,
                "tname"=>$tname,
                "pphone"=>$pphone,
                "token"=>$token
            ];
            $tid = $Testee->add($data);
        }
        else {
            $tid = $testee['id'];
            $testee['group'] = $group;
            $testee['tname'] = $tname;
            $testee['pphone'] = $pphone;
            $testee['token'] = $token;

            $Testee->save($testee);
        }



        session("ntxx_tid", $tid);

        $Submit = M("submit");
        $count = $Submit->where(["testee"=>$tid, "status"=>1])->select();
        if(count($count)>=2){
//            $result["info"]="您已经完成两次考试,分别得分：".$testee['score1'].",".$testee['score2'];
            $result["info"]="您已经完成两次考试,分别得分：".$count[0]['score'].",".$count[1]['score'];
            $result["status"]=0;
            $this->ajaxReturn($result);
        }



        $map['testee'] = $tid;
        $map['status'] = 0;
        $data = $Submit->where($map)->find();
//        dump($map);
		if(!$data){
			$topic = $this->getTopicByGroup();

			foreach($topic as &$v){
				$arr = [1,2,3,4];
				shuffle($arr);
				$v["display1"] = $v["answer".$arr[0]];
				$v["display2"] = $v["answer".$arr[1]];
				$v["display3"] = $v["answer".$arr[2]];
				$v["display4"] = $v["answer".$arr[3]];
				foreach($arr as $kk=>$vv){
					if($vv == $v["answer"]){
						$v["display"] = $kk+1;
						break;
					}
				}
			}
			$data = [
//				"startOn"=>date("Y-m-d H:i:s"),
				"ip"=>get_client_ip(),
				"score"=>0,
				"info"=>serialize($topic),
				"status"=>0,
				"testee"=>$tid,
				"group"=>$group
			];
            $result = M("submit")->add($data);
            dump($data);
		}
		$this->success();
	}
	
    public function index(){
        if(!in_app()){
            $this->display('openapp');
            exit();
        }
		$startTime = "2018-01-21  00:00:00";
		$finishTime = "2018-01-30 23:59:59";

        $btnStatus = '';
        if(strtotime ( $startTime ) > time ()) {
            $btnStatus = "disabled";
        }
        elseif(strtotime ( $finishTime ) < time ()){
            $btnStatus = "disabled";
        }
        $group = M("group")->select();

        $this->assign('OnTime',$btnStatus);
        $this->assign('group',$group);
        $data = $this->_getanswer();
        if($data){

            $startTime = strtotime($data['starton']);
            $now = strtotime(date("Y-m-d H:i:s"));
            $differ = 3600-($now-$startTime);
            $this->assign('seconds',$differ);
            $this->display("answer");
            exit;
        }
        $tid = I("get.tid");
        $Testee = M("testee");
        if($tid) {
            $testee = $Testee->where(["id"=>$tid])->find();
            $this->assign('testee',$testee);
        }
        $token = $this->getToken();
        session("ntxx_token", $token);
        $duplicate = $Testee->where(["token"=>$token])->where("token<> '' and token <> '(null)' and token != 'null'")->find();

        $this->assign('dup',$duplicate);
        $this->assign('token',$token);
        $this->display();
	}
	public function go_deadline(){
        $tid = session("ntxx_tid");
        $map['testee'] = $tid;
        $map['status'] = 0;

        $data["status"]=1;
        $data["finishOn"]=date("Y-m-d H:i:s");
        $sub = M("submit")->where($map)->find();

        M("submit")->where($map)->save($data);

//        $count = M("submit")->where(["testee"=>$tid])->count();
//        M("testee")-> where(["id"=>$tid])->setField('score'.$count,$sub["score"]);

        $Testee = M("testee");
        $count = M("submit")->where(["testee"=>$tid, "status"=>1])->count();
        $Testee->where(["id"=>$tid])->setField('score'.$count,$sub["score"]);
        $testee = $Testee->getById($tid);

        $group = $testee["group"];
        $g_count = $Testee->where('`group`='.$group)->count('`group`');
        $mygroup = M("group")->getById($group);
        if($g_count==$mygroup["pc"]){
            $dataa["full_date"] = date("Y-m-d H:i:s");
            $filter["id"] = $group;
            M("group")->where($filter)->data($dataa)->save();
//                $mygroup->save();
        }

        $result["info"]="您的答题已经结束。得分".$sub["score"];
        $result["status"]=1;
        $this->ajaxReturn($result);
    }
    public function getToken(){
        $zzjjheader = getallheaders()['Zzjj-Header'];
        $headers = explode(",", $zzjjheader);
        $token='';
        foreach ($headers as $value) {
            $kv = explode('=', $value);
            if(strtoupper($kv[0])=='DEVICETOKEN')
                $token = $kv[1];
        }

        return $token;
    }
	private function _getanswer(){
		$tid = session("ntxx_tid");
		if(!$tid) return false;

        $map['testee'] = $tid;
        $map['status'] = 0;

		$data = M("submit")->where($map)->find();

		if(!$data) return false;
		$data["answer"] = unserialize($data["info"]);
		return $data;
	}
	
	public function postanswer(){
        if(!in_app()){
            $result["info"]="请在掌中九江APP中参与竞答。";
            $result["status"]=0;
            $this->ajaxReturn($result);
            exit();
        }
		if(time() >= strtotime("2018-01-30 23:59:59")){
			$this->ajaxReturn(["next"=>0,"info"=>"竞答已结束"]);
			exit;
		}
		if(time() <= strtotime("2018-01-21  00:00:00")){
			$this->ajaxReturn(["next"=>0,"info"=>"竞答尚未开始"]);
			exit;
		}
		$i = I("post.i",0,"intval");
		$data = $this->_getanswer();
		$answer = $data["answer"];
		
		$next = [];
		$thisanswer = [];
		foreach($answer as $k => &$v){
			if($v["join_time"] && !$v["submit_time"] && $i!=-1){
				$v["submit_time"] = time();
				if($v["display"]==$i){
                    $data["score"] +=floatval($v["fra"]);
				}
				else{
					$v["score"] = 0;
				}
				$v["status"] = 1;
				$v["submit"] = $i;
				$thisanswer = [
					"showinfo" => 1,
					"display"=>$v["display"],
				];
			}
			if($i==-1 && $k==0){
				$v["join_time"] = time();
				$thisanswer = [
					"showinfo" => 0,
				];
			}
			if(!$v["status"]){
				if(!$$v["join_time"]){
					$v["join_time"] = time();
				}
				$next = [
					"next"=>1,
					"title"=>$v["title"],
					"pic"=>$v["pic"],
					"display1"=>$v["display1"],
					"display2"=>$v["display2"],
					"display3"=>$v["display3"],
					"display4"=>$v["display4"],
					"index"=>$k+1,
				];
				break;
			}
		}
		
		if(!$next){
			$data["status"]=1;
			$data["finishOn"]=date("Y-m-d H:i:s");
		}
		
		$data["info"]=serialize($answer);
        M("submit")->where(["id"=>$data["id"]])->save($data);
        if($data["status"]==1){
            $Testee = M("testee");
            $tid = session("ntxx_tid");
            $count = M("submit")->where(["testee"=>$tid, "status"=>1])->count();
            $Testee->where(["id"=>$tid])->setField('score'.$count,$data["score"]);
            $testee = $Testee->getById($tid);

            $group = $testee["group"];
            $g_count = $Testee->where('`group`='.$group)->count('`group`');
            $mygroup = M("group")->getById($group);
            if($g_count==$mygroup["pc"]){
                $dataa["full_date"] = date("Y-m-d H:i:s");
                $filter["id"] = $group;
                M("group")->where($filter)->data($dataa)->save();
//                $mygroup->save();
            }
		}
		$result = array_merge($thisanswer,$next);
		$result["score"] = $data["score"];
		$this->ajaxReturn($result);
	}

    public function finish(){
//        $tid = session("ntxx_tid");
//        if(!$tid) $this->error('数据错误，请重试！');
////        $Testee = M("testee");
////        $testee = $Testee->getById($tid);
//
//        $count = M("submit")->where(["testee"=>$tid, "status"=>1])->select();
//        if(count($count)>=2){
//            $dataa["score2"] = $count[1]['score'];
//        }
//        if(count($count)>=1){
//            $dataa["score1"] = $count[0]['score'];
//        }
//        M("testee")->where(["id"=>$tid])->data($dataa)->save();
////        $this->assign("testee",$testee);
//        $this->assign("tid",$tid);
        $this->display();
    }


    public function finish1(){
        $tid = session("ntxx_tid");
        if(!$tid) $this->error('数据错误，请重试！');
//        $Testee = M("testee");
//        $testee = $Testee->getById($tid);
        $count = M("submit")->where(["testee"=>$tid, "status"=>1])->select();
        if(count($count)>=2){
            $this->assign("score2",$count[1]['score']);
            $dataa["score2"] = $count[1]['score'];
        }
        if(count($count)>=1){
            $this->assign("score1",$count[0]['score']);
            $dataa["score1"] = $count[0]['score'];
        }
        M("testee")->where(["id"=>$tid])->data($dataa)->save();
//        $this->assign("testee",$testee);
        $this->assign("tid",$tid);
        $this->display();
    }

    public function search(){
        if(!in_app()){
            $this->display('answer/openapp');
            exit();
        }

        $phone = I("get.phone");
        if(!$phone) $this->error('请正确输入您的电话号码，请重试！');
        $testee = M("testee")->where(["pphone"=>$phone])->find();
        if($testee){
            $tid = $testee['id'];
            $count = M("submit")->where(["testee"=>$tid, "status"=>1])->select();
            if(count($count)>=2){
                $this->assign("score2",$count[1]['score']);
                $dataa["score2"] = $count[1]['score'];
            }
            if(count($count)>=1){
                $this->assign("score1",$count[0]['score']);
                $dataa["score1"] = $count[0]['score'];
            }
            M("testee")->where(["id"=>$tid])->data($dataa)->save();
//        $this->assign("testee",$testee);
            $this->assign("tid",$testee['tname'].':');
            $this->display('finish');
        }
        else{
            $this->error('您输入的电话号码有误，请重试！');
        }
    }
	public function rank(){
		$data = M("submit")->field("name,company,score")->order("score desc,time asc")->limit(100)->select();
		$this->assign("data",$data);
		$this->display();
	}

    public function getTopicByGroup(){
//	    dump($groupId);
        $element = json_decode('{"1": 15, "2": 15, "3": 10}', true);
        $topicData = [];
        foreach ($element as $key => $value){
            $data = M("topic")->where(["category"=>$key])->select();
            shuffle($data);
            $data = array_slice($data, 0, $value);

            if($data)
                $topicData = array_merge($topicData, $data);
        }
        dump($topicData);
        return $topicData;
    }
}